package cn.hj.domain.strategy.service.rule.filter.impl;

import cn.hj.domain.strategy.adapter.repository.IStrategyRepository;
import cn.hj.domain.strategy.model.entity.RuleActionEntity;
import cn.hj.domain.strategy.model.entity.RuleMatterEntity;
import cn.hj.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import cn.hj.domain.strategy.service.annotation.LogicStrategy;
import cn.hj.domain.strategy.service.rule.filter.ILogicalFilter;
import cn.hj.domain.strategy.service.rule.filter.factory.DefaultLogicFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/*
* 抽奖规则-次数锁当用户抽奖次数大于规则限定数，规则拦截。
* */
@Slf4j
@Service
@LogicStrategy(logicMode = DefaultLogicFactory.LogicModel.RULE_LOCK)
public class RuleLockLogicFilter implements ILogicalFilter<RuleActionEntity.RaffleCenterEntity> {

    @Resource
    private IStrategyRepository repository;

    // 用户抽奖次数，后续完成这部分流程开发的时候，从数据库/Redis中读取
    private Long userRaffleCount = 0L;

    @Override
    public RuleActionEntity<RuleActionEntity.RaffleCenterEntity> doFilter(RuleMatterEntity ruleMatterEntity) {
        log.info("规则过滤-次数锁 userId:{} strategyId:{} ruleModel:{}", ruleMatterEntity.getUesrId(), ruleMatterEntity.getStrategyId(), ruleMatterEntity.getRuleModel());

        //查询规则值配置:当前奖品ID，抽奖中规则对应的校验值。如；1、2、6
        String ruleValue = repository.queryStrategyRuleValue(ruleMatterEntity.getStrategyId(), ruleMatterEntity.getAwardId(), ruleMatterEntity.getRuleModel());
        long raffleValue = Long.parseLong(ruleValue);

        //用户抽奖次数大于规则限定数，规则放行。
        if (userRaffleCount >= raffleValue){
            return RuleActionEntity.<RuleActionEntity.RaffleCenterEntity>builder()
                    .code(RuleLogicCheckTypeVO.ALLOW.getCode())
                    .info(RuleLogicCheckTypeVO.ALLOW.getInfo())
                    .build();
        }
        //用户抽奖次数小于规则限定数，规则拦截。
        return RuleActionEntity.<RuleActionEntity.RaffleCenterEntity>builder()
                .code(RuleLogicCheckTypeVO.TAKE_OVER.getCode())
                .info(RuleLogicCheckTypeVO.TAKE_OVER.getInfo())
                .build();
    }
}
